<template>
  <div>
    <el-form ref="form" :model="FormData" :rules="rules" label-width="90px">
      <div style="color: gray; margin-left: 20px">创建时间:{{ FormData.createTime }}</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="sku:">
            <span>{{ FormData.skuNo }}</span>
            <i style="margin: 0 5px" class="el-icon-document-copy" @click="useCopy(FormData.skuNo)"></i>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('库位号') + ''">
            <span>{{ FormData.stockPositionNo }}</span>
            <i style="margin: 0 5px" class="el-icon-document-copy" @click="useCopy(FormData.stockPositionNo)"></i>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('额外sku') + ''">
            <el-input v-model="FormData.skuExtra" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('中文名') + ''" prop="skuNameCn">
            <el-input v-model="FormData.skuNameCn"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('日文名') + ''" prop="skuNameJp">
            <el-input v-model="FormData.skuNameJp"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('英文名') + ''" prop="skuNameEn">
            <el-input v-model="FormData.skuNameEn"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('商品分类')" prop="classId">
            <treeselect
              @open="expandNodeBySelectedItem"
              ref="treeselectRef"
              v-model="FormData.classId"
              :options="menuOptions"
              :show-count="true"
              :placeholder="$t('请选择')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item :label="$t('jan编码') + ''" prop="janCode">
            <el-input disabled v-model="FormData.janCode"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('品牌') + ''" prop="brand">
            <el-input v-model="FormData.brand"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('产品规格') + ''" prop="specification">
            <el-input v-model="FormData.specification"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item :label="$t('长度') + ''" prop="length">
            <!-- <div class="size">{{ FormData.skuLength }}cm</div> -->
            <el-input style="width: 100%" v-model="FormData.skuLength" oninput="value=value.replace(/[^\d.]/g, '')">
              <template slot="suffix">cm</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" prop="width">
          <el-form-item :label="$t('宽度') + ''">
            <!-- <div class="size">{{ FormData.skuWidth }}cm</div> -->
            <el-input style="width: 100%" v-model="FormData.skuWidth" oninput="value=value.replace(/[^\d.]/g, '')">
              <template slot="suffix">cm</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" prop="height">
          <el-form-item :label="$t('高度') + ''">
            <!-- <div class="size">{{ FormData.skuHeight }}cm</div> -->
            <el-input style="width: 100%" v-model="FormData.skuHeight" oninput="value=value.replace(/[^\d.]/g, '')">
              <template slot="suffix">cm</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" prop="weight">
          <el-form-item :label="$t('重量') + ''">
            <!-- <div class="size">{{ FormData.skuWeight }}g</div> -->
            <el-input style="width: 100%" v-model="FormData.skuWeight" oninput="value=value.replace(/[^\d.]/g, '')">
              <template slot="suffix">g</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="5">
          <el-form-item :label="$t('箱规') + ''" prop="box">
            <el-input v-model="FormData.box" oninput="value=value.replace(/[^\d.]/g, '')"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="1" v-if="FormData.box">
          <el-form-item :label="$t('箱子重量') + ''" prop="janCode">
            <div class="">{{ FormData.skuWeight * FormData.box }}g</div>
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="1">
          <el-form-item label-width="90px" v-model="FormData.isExpired" :label="$t('是否会过期')" prop="isExpired">
            <div style="height: 36px; display: flex; align-items: center">
              <el-radio-group v-model="FormData.isExpired">
                <el-radio :label="1">{{ $t('是') }}</el-radio>
                <el-radio :label="0">{{ $t('否') }}</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="5" :offset="1">
          <el-form-item label-width="120px" :label="$t('最近过期时间')" prop="latelyExpiredTime">
            <div>{{ FormData.latelyExpiredTime ? FormData.latelyExpiredTime.split(' ')[0] : '' }}</div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('备注') + ''" prop="remark">
            <el-input type="textarea" :rows="3" v-model="FormData.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('采购备注') + ''" prop="purchaseRemark">
            <el-input type="textarea" :rows="3" v-model="FormData.purchaseRemark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-row>
            <el-col :span="24">
              <el-form-item label-width="100px" :label="$t('最近采购价格') + ''" prop="price">
                <div>{{ FormData.price }} JPY</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label-width="100px" :label="$t('总数量') + ''" prop="stock">
                <div>{{ FormData.stock }}</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="16" style="display: none">
          <div class="card">
            <el-row>
              <div style="font-weight: bold; margin: 0 0 10px 0">{{ $t('设置价格模式') }}</div>
            </el-row>
            <el-form-item label-width="0" prop="priceMode;">
              <el-radio-group @change="resetPriceModeForm" v-model="FormData.priceMode">
                <el-radio :label="1">{{ $t('固定价格') }}</el-radio>
                <el-radio :label="2" style="margin-left: 160px">{{ $t('动态价格') }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-row>
              <el-col :span="12">
                <div class="adjustment" style="margin-right: 40px">{{ $t('用于手动调整云价格') }}</div>
              </el-col>
              <el-col :span="12" style="margin-left: -30px">
                <div class="adjustment">
                  {{
                    $t(
                      '根据采购价格变动（上架时变动）可以设置倍率自动变动（默认倍率是1）例如采购价格是200，倍率是1.2，那么上架时当前在库的云价格就会自动更新成240',
                    )
                  }}
                </div>
              </el-col>
            </el-row>
            <el-row v-if="FormData.priceMode == 1" style="margin-top: 10px; padding: 5px">
              <el-col :span="10">
                <el-form-item label-width="60px" :label="$t('云价格') + ''" prop="cloudPrice">
                  <el-input
                    disabled
                    style="width: 150px"
                    oninput="value=value.replace(/[^.\d]/g,'')"
                    v-model="FormData.cloudPrice"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label-width="60px" :label="$t('价格') + ''" prop="price">
                  {{ FormData.price }}JPY
                </el-form-item>
              </el-col>
            </el-row>
            <div v-if="FormData.priceMode == 2" style="margin-top: 10px; padding: 5px">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" :label="$t('倍率') + ''" prop="multipleRate">
                    <!-- <el-input
                      @change="rateChange"
                      oninput="value=value.replace(/[^.\d]/g,'')"
                      v-model="FormData.multipleRate"></el-input> -->
                    <el-input-number
                      disabled
                      size="mini"
                      @change="rateChange"
                      v-model="FormData.multipleRate"
                      controls-position="right"
                      :precision="2"
                      :min="1"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="60px" :label="$t('价格') + ''" prop="price">
                    {{ FormData.price }}JPY
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label-width="60px" :label="$t('云价格') + ''" prop="cloudPrice">
                    {{ (FormData.multipleRate * FormData.price).toFixed(0) }}JPY
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer">
      <el-button
        type="primary"
        @click="submitForm"
        v-hasPermi="['distribution:skuDistributor:updateSkuDistributorDetails']"
      >
        {{ $t('保存修改') }}
      </el-button>
      <el-button @click="close">{{ $t('关闭') }}</el-button>
    </div>
  </div>
</template>

<script>
import { getSkuDistributorDetails, updateSkuDistributorDetails } from '@/api/distribution/sku/basicInformation'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'ErpDistributionSystemPlusBasicInformation',
  components: { Treeselect },

  data() {
    return {
      /**商品分类菜单树选项 */
      menuOptions: [],
      backFormDate: {},
      FormData: {},
      rules: {
        sku: [{ required: true, message: '请输入sku', trigger: 'blur' }],
        skuExtra: [{ required: true, message: '请输入', trigger: 'blur' }],
        skuNameCn: [{ validator: this.validLength, required: true, trigger: 'change' }],
        skuNameJp: [{ validator: this.validLength, required: false, trigger: 'change' }],
        skuNameEn: [{ validator: this.validLength, required: false, trigger: 'change' }],
        remark: [{ validator: this.validLength, required: false, trigger: 'change' }],
        purchaseRemark: [{ validator: this.validLength, required: false, trigger: 'change' }],
        box: [{ required: true, message: '请输入箱规', trigger: 'blur' }],
      },
    }
  },
  props: {
    skuId: {
      type: String,
      default: '',
    },
  },
  created() {
    this.SkuDistributorDetails()
    this.$getSkuClassList().then((res) => {
      this.menuOptions = res.menuOptions
    })
  },

  methods: {
    /**验证长度 */
    validLength(rule, value, callback) {
      const { field } = rule
      const strLength = value?.length || 0

      // skuNameCn
      if (field == 'skuNameCn') {
        if (!value) {
          return callback(new Error(`请输入`))
        }
        //  长度最大为 255
        if (strLength > 255) {
          return callback(new Error(`文字超长 ${strLength} / 255`))
        }
      }

      // purchaseRemark  255
      if (field == 'purchaseRemark') {
        //  长度最大为 255
        if (strLength > 255) {
          return callback(new Error(`文字超长 ${strLength} / 255`))
        }
      }
      // remark  2000
      if (field == 'remark') {
        //  长度最大为 2000
        if (strLength > 2000) {
          return callback(new Error(`文字超长 ${strLength} / 2000`))
        }
      }

      // 名称 长度最大为 255
      if (field == 'skuNameJp' || field == 'skuNameEn') {
        if (strLength > 255) {
          return callback(new Error(`文字超长 ${strLength} / 255`))
        }
      }
      return callback()
    },
    expandNodeBySelectedItem() {
      const { treeselectRef } = this.$refs

      const setExpanded = (data) => {
        if (data && data.parentNode) {
          data.parentNode.isExpanded = true
        }
        if (data.parentNode && data.parentNode.parentNode) {
          setExpanded(data.parentNode)
        }
      }
      if (treeselectRef) {
        treeselectRef.traverseAllNodesByIndex((node) => {
          if (node.id == this.FormData.classId) {
            this.$nextTick(() => {
              setExpanded(node)
            })
          }
        })
      }
    },
    // 验证数据是否改变
    validFormData() {
      // console.log(this.backFormDate, this.FormData)
      let FormDataChange = null
      if (JSON.stringify(this.backFormDate) == JSON.stringify(this.FormData)) {
        FormDataChange = false
      } else {
        FormDataChange = true
      }
      return FormDataChange
    },

    resetPriceModeForm() {
      this.FormData.cloudPrice = this.backFormDate.cloudPrice
      this.FormData.multipleRate = this.backFormDate.multipleRate
    },
    rateChange(rate) {
      this.FormData.cloudPrice = (this.FormData.price * rate).toFixed(4)
    },
    SkuDistributorDetails() {
      getSkuDistributorDetails({ skuId: this.skuId }).then((res) => {
        this.$parent.$parent.updateSkuImg(res.data.imgUrl)
        this.backFormDate = res.data
        this.backFormDate.multipleRate = Number(this.backFormDate.multipleRate)
        this.FormData = JSON.parse(JSON.stringify(this.backFormDate))
      })
    },
    close() {
      this.$parent.$parent.cancel()
    },
    submitForm() {
      const data = JSON.parse(JSON.stringify(this.FormData))
      if (data.priceMode == 1) {
        data.fixedPrice = data.cloudPrice
      }
      // this.$refs["form"].validate((valid) => {
      //   if (!valid) return;
      //   // TODO 提交表单
      //   updateSkuDistributorDetails(this.FormData).then((res) => {
      //     this.$message({
      //       type: "success",
      //       message: res.msg,
      //     });
      //     this.SkuDistributorDetails();
      //   });
      // });

      this.$refs['form'].validate((valid) => {
        if (valid) {
          updateSkuDistributorDetails(data).then((res) => {
            this.$message({
              type: 'success',
              message: res.msg,
            })
            this.SkuDistributorDetails()
          })
        }
      })
    },
    cancel() {},
  },
}
</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
  margin-bottom: 16px !important;
}
::v-deep .el-radio-group {
  display: flex;
}

.size {
  width: 100%;
  text-align: center;
}

.card {
  flex: 1;
  border-radius: 2px;
  padding: 10px;
  border: solid 1px rgba(0, 0, 0, 0.1);
}

.adjustment {
  border-radius: 2px;
  padding: 4px;
  background-color: rgb(225, 234, 252);
}

.footer {
  margin-top: 10px;
  float: right;
}

.vue-treeselect__menu-container {
  .vue-treeselect__menu {
    width: 150px;
  }
}
</style>
